import { join } from 'path';
import {
    app,
    BrowserWindow,
    ipcMain,
    dialog
} from 'electron';
import axios from 'axios';

const isDev = process.env.npm_lifecycle_event === "app:dev" ? true : false;

async function handleFileOpen() {
    const { canceled, filePaths } = await dialog.showOpenDialog({ title: "Open File" })
    if (!canceled) {
        return filePaths[0]
    }
}

let mainWindow: any
function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: 1920,
        height: 1080,
        
        minimizable: true,//取消Windows自带的关闭最小化
        maximizable: false,
        autoHideMenuBar: true,
        icon: '../../assets/logo.ico',
        resizable: false, //禁止改变主窗口尺寸
        movable: false, //是否移动
        webPreferences: {
            preload: join(__dirname, '../preload/preload.js'),
        },
        // fullscreen: true, //设置全屏
    });

    // and load the index.html of the app.
    if (isDev) {
        mainWindow.loadURL('http://localhost:3000');// Open the DevTools.
        // mainWindow.webContents.openDevTools();
    } else {
        mainWindow.loadFile(join(__dirname, '../../index.html'));
        // mainWindow.webContents.openDevTools();
    }
    
    mainWindow.on('close', function (e: any) {
        let response = dialog.showMessageBoxSync(mainWindow, {
            type: 'question',
            buttons: ['Yes', 'No'],
            title: '退出',
            message: '确定退出?'
        });
        e.preventDefault()
        //点击按钮 是
        if(response == 0) {
            axios.post('http://localhost:5100/DMS/KSKH/Exit').then((res: any) => {
                if(res.data.code == 200){
                    app.exit()
                }else{
                    e.preventDefault()
                }
            })
        }
    });
    // mainWindow.loadURL( //this doesn't work on macOS in build and preview mode
    //     isDev ?
    //     'http://localhost:3000' :
    //     join(__dirname, '../../index.html')
    // );
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    ipcMain.handle('dialog:openFile', handleFileOpen)
    createWindow()
    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
}